<template>
  <a-tabs :default-active-key="activeIndex" @change="handleTabSelect">
    <a-tab-pane key="1" tab="生产任务">
      <task-table
        :columns="this.isManager?this.$staticMenu.productHistoryColumns:this.$staticMenu.productHistoryNoActionColumns"
        :url="tableUrl"
        selectType="checkbox"
        :type="tableType"
        :params="tableParams"
        :size="pageSize"
        :sizeOptions="pageSizeOptions"
        :rowSelection="rowSelection"
        rowKeyName="id"
        ref="productTable"
        @onSelect="tableOnSelect"
      >
        <!-- 补充搜索条件 -->
        <a-row slot="searchCri">
          <a-col :span="5">
            <a-input class="searchCriteria" placeholder="任务名称（仅支持数字、字母和汉字）" @keydown.native="keydown($event)" v-model="tableParams.name"  onkeyup="value=value.replace(/[\s+`~!@#$%^&*()_\-+=<>?:{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/^[a-zA-Z0-9_()（）\u4e00-\u9fa5]{1,50}$/,''))"/>
          </a-col>
          <a-col :span="6">
            <a-button type="primary" @click="criteriaSearchProduct">
              <a-icon type="search" />查询
            </a-button>
            <a-button @click="clearCriteriaProduct">
              <a-icon type="sync" />重置
            </a-button>
            <a-button type="primary" @click="creatProduct" >
              创建生产任务
            </a-button>
          </a-col>
          <a-col :span="13" style="text-align:right" v-if="this.isManager">
            <a-button type="primary" @click="acceptProduct" >
              <a-icon type="check" />审批通过
            </a-button>
            <a-button type="danger" @click="rejectProduct" >
              <a-icon type="close" />拒绝
            </a-button>
          </a-col>
        </a-row>
        <!-- end -->
        <span slot="productname" slot-scope="props">
            <a-tooltip placement="top">
              <template slot="title">
                <span>{{props.record.name}}</span>
              </template>
              <span class="ellipsis">{{props.record.name}}</span>
            </a-tooltip>
       </span>
        <span slot="statusSwitch" slot-scope="props">
          <span v-if="props.record.status=='审批通过'" class="text-success">{{ props.record.status }}</span>
          <span v-else-if="props.record.status=='审批拒绝'" class="text-danger">{{ props.record.status }}</span>
          <span v-else-if="props.record.status=='未审批'">{{ props.record.status }}</span>
          <span v-else-if="props.record.status=='任务完成'" class="text-success">{{ props.record.status }}</span>
          <span v-else  class="text-success">{{ props.record.status }}</span>
        </span>
         <span slot="roleName" slot-scope="props">
            <a-tooltip placement="top">
              <template slot="title">
                <span>{{props.record.taskdocument}}</span>
              </template>
              <span class="ellipsis">{{props.record.taskdocument}}</span>
            </a-tooltip>
        </span>

              <!-- 补充表格每行的操作 -->
         <span slot="tableRowAct" slot-scope="props">
           <a-button class="ant-tag" @click="showDetail(props.record)">
              <a-icon type="small-dash"/> 详情
            </a-button>
          <a v-if="props.record.status==='未审批'">
            <span class="ant-tag" @click="editFlow(props.record)">
              <a-icon type="edit"/> 编辑
            </span>
          </a>
           <a v-if="props.record.status==='审批通过'">
            <span class="ant-tag ant-tag-green" @click="tranPro(props.record)">
              <a-icon type="snippets"/> 任务下发
            </span>
          </a>
        </span>
      </task-table>
      <modal
        ref="flowModalForm"
        :flowTitle="modalFlowTitle"
        :flowVisible="modalFlowVisible"
        :id="recordId"
        @cancel="handleCancel"
        @ok="handleOk"
      >
      </modal>
      <proModal
        :title="modalProTitle"
        :visible="modalProVisible"
        @cancel="handleProCancel"
        @ok="handleProOk"
      ></proModal>
      <showpro
        :title="showProTitle"
        :visible="showProVisible"
        :reocrd="selectreocrd"
        @cancel="showProCancel"
        @ok="showProOk"
      ></showpro>
      <tranProductModal
      :title="tranProTitle"
      :visible="tranProVisible"
      :record="tranreocrd"
      @cancel="tranProCancel"
      @ok="tranProOk"
      ></tranProductModal>
    </a-tab-pane>
    <a-tab-pane key="2" tab="评估任务" force-render>
      <unit-table
        :columns="this.isManager?this.$staticMenu.estimateHistoryColumns:this.$staticMenu.estimateHistoryNoActionColumns"
        :url="tableEstimateUrl"
        selectType="checkbox"
        :type="tableEstimateType"
        :params="tableParamsEstimate"
        :size="pageSize"
        :sizeOptions="pageSizeOptions"
        :rowSelection="rowSelection1"
        rowKeyName="id"
        ref="estimateTable"
        @onSelect="tableOnSelect"
      >
        <!-- 补充搜索条件 -->
        <a-row slot="searchCri">
          <a-col :span="3">
            <a-select v-model="tableParamsEstimate.classify" class="searchCriteria">
              <a-select-option v-for="(item, key) of classify" :key="item" :value="item">{{ item }}</a-select-option>
            </a-select>
          </a-col>

          <a-col :span="5">
            <a-input class="searchCriteria" placeholder="任务名称（仅支持数字、字母和汉字）" v-model="tableParamsEstimate.name"  @keydown.native="keydown($event)" onkeyup="value=value.replace(/[\s+`~!@#$%^&*()_\-+=<>?:{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/^[a-zA-Z0-9_()（）\u4e00-\u9fa5]{1,50}$/,''))" />
          </a-col>
          <a-col :span="6">
            <a-button type="primary" @click="criteriaSearchEstimate">
              <a-icon type="search" />查询
            </a-button>
            <a-button @click="clearCriteriaEstimate">
              <a-icon type="sync" />重置
            </a-button>
            <a-button type="primary" @click="creatEstimate" >
              创建评估任务
            </a-button>
          </a-col>
          <a-col :span="10" style="text-align:right" v-if="this.isManager">
            <a-button type="primary" @click="acceptEstimate">
              <a-icon type="check" />审批通过
            </a-button>
            <a-button type="danger" @click="rejectEstimate">
              <a-icon type="close" />拒绝
            </a-button>
          </a-col>
        </a-row>
        <span slot="estiname" slot-scope="props">
            <a-tooltip placement="top">
              <template slot="title">
                <span>{{props.record.name}}</span>
              </template>
              <span class="ellipsis">{{props.record.name}}</span>
            </a-tooltip>
       </span>
        <span slot="statusSwitch" slot-scope="props">
          <span v-if="props.record.status=='审批通过'" class="text-success">{{ props.record.status }}</span>
          <span v-else-if="props.record.status=='审批拒绝'" class="text-danger">{{ props.record.status }}</span>
          <span v-else-if="props.record.status=='未审批'">{{ props.record.status }}</span>
          <span v-else-if="props.record.status=='任务完成'" class="text-success">{{ props.record.status }}</span>
          <span v-else  class="text-success">{{ props.record.status }}</span>
        </span>
              <!-- 补充表格每行的操作 -->
         <span slot="tableRowAct" slot-scope="props">
           <a-button class="ant-tag" @click="showEstiDetail(props.record)">
              <a-icon type="small-dash"/> 详情
            </a-button>
           <a v-if="props.record.status=='审批通过'">
            <span class="ant-tag ant-tag-green" @click="tranEsti(props.record)">
              <a-icon type="snippets"/> 任务下发
            </span>
          </a>
             <a v-if="props.record.status=='任务完成'">
            <span class="ant-tag ant-tag-green" @click="showReport(props.record)">
              <a-icon type="snippets"/> 结果展示
            </span>
          </a>
        </span>
        <!-- end -->

      </unit-table>
      <estiModal
        :title="modalEstiTitle"
        :visible="modalEstiVisible"
        @cancel="handleEstiCancel"
        @ok="handleEstiOk"
      ></estiModal>
      <showEsti
        :title="showEstiTitle"
        :visible="showEstiVisible"
        :reocrd="selectEsti"
        @cancel="showEstiCancel"
        @ok="showEstiOk">
      </showEsti>
      <showReportModal
      :title="showReportTitle"
      :visible="showReportVisible"
      :reocrd="Jsondata"
      @cancel="showReportCancel"
      @ok="showReportOk"
      ></showReportModal>
    </a-tab-pane>
  </a-tabs>

</template>

<script>
import {
  GETPRODUCTLIST,
  PRODUCTACCEPT,
  PRODUCTREJECT,
  GETESTIMATELIST,
  GETALLCLASSIFY,
  ESTIMATEACCEPT,
  ESTIMATEREJECT,
  GETPRODUCTSELECT,
  TRANSESTIMATE,
  CALLBACKESTI
} from '@/../static/js/apis.js';
import unitTable from '@/common/tableCheck';
import taskTable from '@/common/tableCheck1';
import modal from "./editFlowModal"
import global from '@/../static/global.vue'
import proModal from './productModal'
import showpro from './showProModal'
import estiModal from './estimateModal'
import showEsti from './showEstiModal'
import tranProductModal from "./tranProductModal";
import showReportModal from "./showReportModal";
export default {
  inject: ['reload'], // 注入App里的reload方法
  name: 'allUnit',
  components: {
    unitTable,
    taskTable,
    modal,
    proModal,
    showpro,
    estiModal,
    showEsti,
    tranProductModal,
    showReportModal
  },
  data () {
    return {
      tableSelectedKeys: [],
      tableUrl: GETPRODUCTLIST.url, // 调用表格组件，必须参数，后台数据接口
      tableType: GETPRODUCTLIST.type, // 调用表格组件，必须参数，后台方法方法（get，post）
      tableEstimateUrl: GETESTIMATELIST.url, // 调用表格组件，必须参数，后台数据接口
      tableEstimateType: GETESTIMATELIST.type, // 调用表格组件，必须参数，后台方法方法（get，post）
      pageSize: 15,
      pageSizeOptions: ['15', '20', '40'],
      /* 调用表格组件，可选参数，其他相关搜索条件 */
      tableParams: {
        name: '',
        creator:
          localStorage.getItem('role').indexOf('0') > -1 ? '' : localStorage.getItem('username')
      },
      tableParamsEstimate: {
        classify: '全部分类',
        name: '',
        creator:
          localStorage.getItem('role').indexOf('0') > -1 ? '' : localStorage.getItem('username')
      },
      estimateParams:{
        name:'',
        taskid:'',
        starttime:'',
        endtime:'',
        type:'',
        data:'任务',
        demandDes:'评估任务',
        case:{},
        target:[1,2]
      },
      Jsondata:new Object(),
      classify: [],
      activeIndex: '1',
      userRole: localStorage.getItem('role'),
      modalFlowTitle:'',
      modalFlowVisible:false,
      recordId:'',
      modalProTitle:'',
      modalProVisible:false,
      showProTitle:'',
      showProVisible:false,
      modalEstiTitle:'',
      modalEstiVisible:false,
      selectreocrd:'',
      tranreocrd:'',
      selectEsti:'',
      showEstiTitle:'',
      showEstiVisible:false,
      tranProTitle:'',
      tranProVisible:false,
      showReportTitle:'',
      showReportVisible:false
    }
  },
  computed: {
    // 判断是否管理员
    isManager () {
      return global.isManager(global.SYS_BUSINSESS_MANAGE)
    },
    rowSelection () {
      return {
        selectedRowKeys: this.tableSelectedKeys || [], // 选中行的key当props传值过来时，默认选中
        selectedRows: [], // 选中行的内容
        onChange: (selectedRowKeys, selectedRows) => {
          this.rowSelection.selectedRowKeys = selectedRowKeys
          this.rowSelection.selectedRows = selectedRows
          this.tableOnSelect(selectedRowKeys, selectedRows)
        },
        getCheckboxProps: record => ({
          props: {
            disabled: record.status !== '未审批' // Column configuration not to be checked
          }
        })
      }
    },
     rowSelection1 () {
      return {
        selectedRowKeys: this.tableSelectedKeys || [], // 选中行的key当props传值过来时，默认选中
        selectedRows: [], // 选中行的内容
        onChange: (selectedRowKeys, selectedRows) => {
          this.rowSelection1.selectedRowKeys = selectedRowKeys
          this.rowSelection1.selectedRows = selectedRows
          this.tableOnSelect(selectedRowKeys, selectedRows)
        },
        getCheckboxProps: record => ({
          props: {
            disabled: record.status !== '未审批' // Column configuration not to be checked
          }
        })
      }
    },
  },
  methods: {
    keydown(e){
      if(e.keyCode==32){
        e.returnValue=false
      }
    },
    /* 表格checkbox选中事件 */
    tableOnSelect (selectedRowKeys, selectedRows) {
      this.tableSelectedKeys = selectedRowKeys
    },
    /* 查询按钮 */
    criteriaSearchProduct () {
      this.$refs.productTable.fetch(1)
    },
    /* 查询按钮 */
    criteriaSearchEstimate () {
      this.$refs.estimateTable.fetch(1)
    },
    /* 重置按钮 */
    clearCriteriaProduct () {
      this.tableParams.name = '';
      this.$refs.productTable.rowSelection.onChange([ ],[ ])
      this.criteriaSearchProduct()
    },
    /* 重置按钮 */
    clearCriteriaEstimate () {
      this.tableParamsEstimate.classify = '全部分类';
      this.tableParamsEstimate.name = '';
      this.$refs.estimateTable.rowSelection.onChange([ ],[ ])
      this.criteriaSearchEstimate()
    },
    getStaticData () {
      let self = this
      GETALLCLASSIFY('', function (res) {
        self.classify = res
      })
    },
    handleTabSelect (key) {
      localStorage.setItem('activeIndex', key)
    },
    creatProduct(){
      console.log(1)
      let self=this
      self.modalProTitle="创建生产任务"
      self.modalProVisible=true;
    },
    creatEstimate(){
      // console.log("estimate")
      let self=this
      self.modalEstiTitle="创建评估任务"
      self.modalEstiVisible=true;
    },
    acceptProduct () {
      let self = this
      const selectedRowKeys = self.tableSelectedKeys
      var params = {
        ids: selectedRowKeys,
        userid: parseInt(localStorage.getItem('userid'))
      }
      if (selectedRowKeys.length > 0) {
        PRODUCTACCEPT(params, function (res) {
          self.$message.success(res.message)
          self.reload()
        })
      } else {
        self.$message.warning('请在表格中勾选要审批的数据！')
      }
    },
    rejectProduct () {
      let self = this
      const selectedRowKeys = self.tableSelectedKeys
      var params = {
        ids: selectedRowKeys,
        userid: parseInt(localStorage.getItem('userid'))
      }
      if (selectedRowKeys.length > 0) {
        PRODUCTREJECT(params, function (res) {
          self.$message.success(res.message)
          self.reload()
        })
      } else {
        self.$message.warning('请在表格中勾选要审批的数据！')
      }
    },
    acceptEstimate () {
      let self = this
      const selectedRowKeys = self.tableSelectedKeys
      var params = {
        ids: selectedRowKeys,
        userid: parseInt(localStorage.getItem('userid'))
      }
      if (selectedRowKeys.length > 0) {
        ESTIMATEACCEPT(params, function (res) {
          self.$message.success(res.message)
          self.reload()
        })
      } else {
        self.$message.warning('请在表格中勾选要审批的数据！')
      }
    },
    rejectEstimate () {
      let self = this
      const selectedRowKeys = self.tableSelectedKeys
      var params = {
        ids: selectedRowKeys,
        userid: parseInt(localStorage.getItem('userid'))
      }
      if (selectedRowKeys.length > 0) {
        ESTIMATEREJECT(params, function (res) {
          self.$message.success(res.message)
          self.reload()
        })
      } else {
        self.$message.warning('请在表格中勾选要审批的数据！')
      }
    },
    handleOk (e) {
      this.modalFlowVisible = false
    },
    handleCancel(e) {
      this.modalFlowVisible = false
    },
    handleProOk (e) {
      this.modalProVisible = false
    },
    handleProCancel(e) {
      this.modalProVisible = false
    },
    handleEstiOk (e) {
      this.modalEstiVisible = false
    },
    handleEstiCancel(e) {
      this.modalEstiVisible = false
    },
    showProOk (e) {
      this.showProVisible = false
    },
    showProCancel(e) {
      this.showProVisible = false
    },
    tranProOk (e) {
      this.tranProVisible = false
    },
    tranProCancel(e) {
      this.tranProVisible = false
    },
    showEstiOk (e) {
      this.showEstiVisible = false
    },
    showEstiCancel(e) {
      this.showEstiVisible = false
    },
    showReportOk (e) {
      this.showReportVisible = false
    },
    showReportCancel(e) {
      this.showReportVisible = false
    },
    showDetail(record){
      let self=this
      console.log(record)
      GETPRODUCTSELECT({id:record.id},function(res){
        self.selectreocrd = res.obj
        console.log(self.selectreocrd);
      })
      self.showProTitle=record.name
      self.showProVisible = true
    },
    showEstiDetail(record){
      let self=this
      console.log(record)
      self.selectEsti=record
      self.showEstiTitle=record.name
      self.showEstiVisible=true

    },
    showReport(record){
      let self = this
      self.Jsondata=JSON.parse(record.report)
      self.showReportTitle=record.name
      self.showReportVisible=true
    },
    tranEsti(record){
    let self =this
       console.log(record)
      // values.name=record.name
      // values.taskid=record.id
      // values.starttime=record.starttime
      // values.endtime=record.endtime
      // values.type=record.taskClassify taskPath
      self.estimateParams.name=record.name
      self.estimateParams.taskid=record.id
      self.estimateParams.starttime=record.starttime
      self.estimateParams.endtime=record.endtime
      self.estimateParams.type=record.taskClassify
      self.estimateParams.data=record.taskPath
      self.estimateParams.demandDes=record.taskdes
      if(record.taskClassify == "服务" ){
        self.estimateParams.cases={
          services: {
            data: [ {
              name: record.name,
              ...record.data
            }]
          }
        }
      } else if (record.taskClassify == "应用"){
        self.estimateParams.cases = {
          application: {
            data: [{
              name: record.name,
              expectedResult: record.data.content
            }]
          }
        }
      } else if (record.taskClassify == "数据") {
        self.estimateParams.cases = {
          mapdata: {
            data: [{
              name: record.name,
              expectedResult: record.data.content
            }]
          }
        }
      }
      TRANSESTIMATE(self.estimateParams,function(res){
        let msg =res.message
        if (res.code == '200'){
          let params = {
            taskid: record.id,
            status: '任务已下发'
          }
          CALLBACKESTI(params,function (res){
            if (res.code == '200'){
              //self.$emit("cancel", e)
              self.$message.success(msg);
              self.reload()
            }
          })
        }
        //alert(res.message)
      })

    },
    tranPro(record){
      let self=this
      console.log(record)
      self.tranreocrd=record
      self.tranProTitle=record.name
      self.tranProVisible=true
      // self.productParams.name=record.name
      // self.productParams.taskid=record.id
      // self.productParams.starttime=record.starttime
      // self.productParams.endtime=record.endtime
      // self.productParams.area=record.area
      // self.productParams.areaname=record.taskdocument
      // self.productParams.taskNum=record.taskNum
      // self.productParams.taskDetail=record.taskDetail
      // console.log(self.productParams)
      // TRANSPRODUCT(self.estimateParams,function(res){
      //   self.$message(res.message);
      // })

    },

    editFlow(record){
      this.recordId=record.id
      console.log(record.id)
      console.log(this.recordId)
      this.modalFlowTitle=record.name
      this.modalFlowVisible = true
      this.$nextTick(() => {
          this.$refs.flowModalForm.getStaticData()
       })
    }
  },
  created () {
    this.getStaticData()
    let activeIndex = localStorage.getItem('activeIndex')
    this.activeIndex = activeIndex
  },
  // 只能输入汉字、英文、数字
  btKeyDown(e) {
    e.target.value = e.target.value.replace(/^[a-zA-Z0-9_()（）\u4e00-\u9fa5]{1,50}$/,"");
  },
  //限制输入特殊字符
  btKeyUp(e) {
    e.target.value = e.target.value.replace(/[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/,"");
  }

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.searchCriteria {
  width: 90%;
}
.actionBtn button:not(:last-child),
.ant-row button:not(:last-child) {
  margin-right: 20px;
}
/deep/ .ant-tabs-nav-wrap {
  text-align: center;
}
/deep/.ant-tabs .ant-tabs-top-content > .ant-tabs-tabpane{
  overflow-x:scroll;
}
</style>
